package com.daykw.douyin.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoInfo;
import com.daykw.douyin.model.VideoTask;
import com.daykw.douyin.utils.RadomU;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoInfoThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoInfoThread.class);
	private SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");

	@Override
	public void run() {

		try {
			NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);

			int m = RadomU.getInstance().getValue();
			String node = "1";
			int v = m % 6;

			if (v == 0) {
				node = "0";
			} else if (v == 1) {
				node = "1";
			} else if (v == 2) {
				node = "2";
			} else if (v == 3) {
				node = "3";
			} else if (v == 4) {
				node = "4";
			} else if (v == 4) {
				node = "5";
			}
			// .and("node", "=", node)
			List<VideoTask> tasks = dao.query(VideoTask.class,
					Cnd.where("info_status", "=", 0).limit(1, 10).desc("infoby"));

			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();

			String[] uas = {
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
					"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
					"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
					"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
					"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
					"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
					"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
					"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
					"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
					"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
					"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
					"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
					"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
					"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
					"Mozilla/5.0 (Macintosh; U; Mac OS X Mach-O; en-US; rv:2.0a) Gecko/20040614 Firefox/3.0.0 ",
					"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3",
					"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5",
					"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.14) Gecko/20110218 AlexaToolbar/alxf-2.0 Firefox/3.6.14",
					"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",
					"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"

			};
			for (VideoTask task : tasks) {
				List<Record> cookies = dao.query("t_cookie", Cnd.wrap("WHERE status=1 "));
				if (cookies == null || cookies.size() == 0) {
					logger.info("##########哎呦，cookie没有了");
					return;
				}

				int random = org.apache.commons.lang3.RandomUtils.nextInt(0, cookies.size());

				Record cookie = cookies.get(random);
				Integer count = cookie.getInt("count", 0);
				String c = cookie.getString("cookie");
				String cname = cookie.getString("name");
				headers.put("Cookie", c);
				VideoInfo video = dao.fetch(VideoInfo.class, Cnd.where("kw_id", "=", task.getKw_id()));

				try {
					int r = this.getRnum(uas.length);
					String ua = uas[r];

					headers.put("User-Agent", ua);
					headers.put("Host", "dy.feigua.cn");

//					String infourl = "https://miniapi.feigua.cn/api/v1/aweme/detail?sessionId=9eb93754a3f94055a5da503dff6f9864&awemeId="
//							+ task.getKw_id() + "&sign=9ece";
					String html = http.get(task.getInfo_url(), headers);
					if (html.indexOf("哎呦，访问太频繁了，请稍后再试") >= 0 || html.indexOf("你的访问过于频繁") >= 0) {
						int min = 60000;
						int sleep = min * 30;
						// dao.update("t_cookie", Chain.make("status", "0"), Cnd.where("name", "=",
						// cname));
						logger.info("##########哎呦，访问太频繁了，请稍后再试，暂停" + (sleep / 60000) + "分钟，cookie:" + cname);
						Thread.sleep(sleep);
						dao.update("t_cookie", Chain.make("count", 0), Cnd.where("count", ">", 0));
						continue;
					}
					Document doc = Jsoup.parse(html);

					Elements loginBtn = doc.select("a.login.hvr-ripple-out.js-douyin-login");
					if (loginBtn.isEmpty()) {
						String img = doc.select("div.details-hd-cover img").attr("src");
						String title = null;
						try {
							title = doc.select("dl.details-info-content dt").first().ownText();
						} catch (Exception e) {
							logger.info("标题出错:" + doc.select("dl.details-info-content").html());
						}

						Elements scripts = doc.getElementsByTag("script");
						String productid = null;

						for (Element s : scripts) {

							String script = s.toString();
							if (script.indexOf("promotionId") > 0) {
								String[] sc = script.split("\r\n");
								for (String row : sc) {
									if (row.indexOf("promotionId") > 0) {

										productid = row.substring(row.indexOf("'") + 1, row.lastIndexOf("'"));

										break;
									}

								}
							}
						}

						String tag = doc.select("div.mask a.js-hotKeyWord").text();
						String video_url = doc.select("div.mask div.play-content a.btn-play").attr("href");
						// FileWriteUtils.wirteFile("D:\\douyin.html", doc.html());
						String like = doc.select("div.mask div.some-index span").get(0).text();
						String comments = doc.select("div.mask div.some-index span").get(1).text();
						String reply = doc.select("div.mask div.some-index span").get(2).text();
						if (StringUtils.isEmpty(video.getKw_head_image())) {
							video.setKw_head_image(img);
						}
						video.setKw_product_id(productid);
						video.setText_content(title);
						video.setKw_url(video_url);
						video.setLike_num(like);
						video.setCmt_num(comments);
						video.setRep_num(reply);
						tag = tag.replace(" ", ",");
						video.setKw_tags(tag);
						String pubtime = doc.select("div.mask dl.details-info-content").text();
						pubtime = pubtime.substring(pubtime.indexOf("发布时间：") + 5, pubtime.indexOf(" 数据更新时间："));

						Date pubdate = sd.parse(pubtime);
						video.setPub_time(pubdate);
						video.setUdate(Long.parseLong(fmt.format(new Date())));
						dao.updateIgnoreNull(video);

						dao.update(VideoTask.class, Chain.make("info_status", 2),
								Cnd.where("kw_id", "=", video.getKw_id()));

						int time = this.getRnum(6) * 1000;
						int sleep = time;
						count = count + 1;
						dao.update("t_cookie", Chain.make("count", count), Cnd.where("name", "=", cname));
						logger.info("##########视频详情抓完，暂停" + (sleep / 1000) + "秒，cookie:" + cname);
						Thread.sleep(sleep);
					} else {
						dao.update("t_cookie", Chain.make("status", 0), Cnd.where("name", "=", cname));

						logger.info("##########视频cookie失效，cookie:" + cname);
					}

					// logger.info("##########" + task.getKw_id() + "视频详情抓完,cookie:" + cname);

				} catch (Exception e) {

					logger.error("", e);
					dao.update(VideoTask.class, Chain.make("info_status", 3),
							Cnd.where("kw_id", "=", video.getKw_id()));
				}

				// Thread.sleep(sleep);

			}

			// System.out.println(ret);

		} catch (Exception e) {

			logger.error("", e);
		}

	}

	private int getRnum(int max) {
		int x = (int) (Math.random() * max);
		return x;
	}
}
